<template>
  <div class="container">
    <!-- 头像区域 -->
    <button class="login-btn" v-if="!userinfo.openId" open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="doLogin">获取用户信息</button>
    <div v-else class="userinfo">
      <img :src="userinfo.avatarUrl">
      <p>{{ userinfo.nickName }}</p> 
    </div>
    <!-- 时间组件 -->
    <YearProgress></YearProgress>

    <!-- 添加 -->
    <button v-if="userinfo.openId" class="btn" @click="scanBook">添加图书</button>

  </div>
</template>

<script type="text/ecmascript-6">
import YearProgress from '@/components/YearProgress'
import { showSuccess, post, showModal } from '@/util'
import qcloud from 'wafer2-client-sdk'
import config from '@/config'

export default {
  data () {
    return {
      userinfo: {
        avatarUrl: '../../../static/img/unlogin.png',
        nickName: ''
      }
    }
  },
  components: {
    YearProgress
  },
  created () {
    // let that = this;
    // 获取缓存中的用户信息
    let userinfo = wx.getStorageSync('userinfo')
    if (userinfo) {
      this.userinfo = userinfo
    }
  },
  methods: {
    // 扫码
    scanBook () {
      var that = this
      wx.scanCode({
        success: res => {
          if (res.result) {
            that.addBook(res.result)
          }
        }
      })
    },

    // 添加图书
    async addBook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openId
      })
      showModal('添加成功', `${res.title}添加成功`)
    }
  },

  // 登陆请求
  doLogin: function (e) {
    let that = this
    const session = qcloud.Session.get()

    // 设置登陆url
    qcloud.setLoginUrl(config.loginUrl)

    if (session) {
      // 第二次登录
      // 或者本地已经有登录态
      // 可使用本函数更新登录态
      qcloud.loginWithCode({
        success: res => {
          showSuccess('登陆成功')
          that.userinfo = res
        },
        fail: err => {
          console.log('登录失败', err)
        }
      })
    } else {
      // 首次登录
      qcloud.login({
        success: res => {
          showSuccess('登陆成功')
          wx.setStorageSync('userinfo', res)
          that.userinfo = res
        },
        fail: err => {
          console.log('登录失败', err)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 0 30rpx;
  .login-btn {
    margin: 200rpx;
  }
  .userinfo {
    margin-top: 100rpx;
    text-align: center;
    img {
      width: 150rpx;
      height: 150rpx;
      margin: 20rpx;
      border-radius: 50%;
    }
  }
}
</style>
